# -*- coding: utf-8 -*-
from flask import render_template,session,flash,redirect,url_for,abort,request
from . import blog
from ..db.dbConnection import find_all_comment,insert_comment
@blog.route('/blog/<username>')
def hello_world(username):
    return 'Hello %s!'%username


@blog.route('/blog')
def show_entries():
    commentList = find_all_comment()
    entries = [dict(title=row['title'], text=row['text']) for row in commentList]
    return render_template('show_entries.html', entries=entries)


@blog.route('/blog/login',methods=['GET','POST'])
def login():
    error = None
    if request.method == 'POST':
        session['logged_in'] = True
        flash('You were logged in')
        return redirect(url_for('blog.show_entries'))
    else:
        return render_template('login.html', error=error)


@blog.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)
    if insert_comment(request.form['title'],request.form['text']):
        flash('New entry was successfully posted')
    else:
        flash('New entry was posted failesd')
    return redirect(url_for('blog.show_entries'))


@blog.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('blog.show_entries'))